package com.pactera.madp.cp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.admin.api.vo.SysFileVo;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.common.security.util.SecurityUtils;
import com.pactera.madp.common.sequence.sequence.Sequence;
import com.pactera.madp.cp.api.dto.prod.ProdDto;
import com.pactera.madp.cp.api.dto.prod.UpdateIntroDTO;
import com.pactera.madp.cp.api.entity.*;
import com.pactera.madp.cp.api.entity.prod.*;
import com.pactera.madp.cp.api.entity.sync.SyncAnnualizedRateInfoEntity;
import com.pactera.madp.cp.api.entity.sync.SyncCycleSetInfoEntity;
import com.pactera.madp.cp.api.feign.RemoteDeptService;
import com.pactera.madp.cp.api.vo.ProdVo;
import com.pactera.madp.cp.api.vo.prod.BusinessCardVO;
import com.pactera.madp.cp.api.vo.prod.ProdDepositVo;
import com.pactera.madp.cp.api.vo.prod.ProdGroupVo;
import com.pactera.madp.cp.common.constant.ProductConstant;
import com.pactera.madp.cp.common.enums.ProductGroupEnum;
import com.pactera.madp.cp.common.util.FileUtils;
import com.pactera.madp.cp.common.util.WxApiUtils;
import com.pactera.madp.cp.common.util.file.FilesUtil;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.mapper.prod.*;
import com.pactera.madp.cp.mapper.sync.SyncAnnualizedRateInfoMapper;
import com.pactera.madp.cp.mapper.sync.SyncCycleSetInfoMapper;
import com.pactera.madp.cp.mapper.sync.SyncStdDataInfoMapper;
import com.pactera.madp.cp.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import static com.pactera.madp.cp.common.constant.WxApiConst.API_GET_FILE_TO_TEMP;
import static com.pactera.madp.cp.common.util.WxApiUtils.getAccessTokenEmployee;

/**
 * 华融湘江产品管理服务实现类
 *
 * @author HuHao
 * @date 2022/3/16 9:31
 */
@Service
public class ProdServiceImpl extends ServiceImpl<ProdMapper, ProdEntity> implements ProdService {

    @Autowired
    private ProdDepositMapper prodDepositMapper;
    @Autowired
    private ProdGroupMapper prodGroupMapper;
    @Autowired
    private ProdDeptService prodDeptService;
    @Autowired
    private SynProdInfoMapper synProdInfoMapper;
    @Autowired
    private SyncCycleSetInfoMapper syncCycleSetInfoMapper;
    @Autowired
    private SyncStdDataInfoMapper syncStdDataInfoMapper;
    @Autowired
    private SyncAnnualizedRateInfoMapper syncAnnualizedRateInfoMapper;
    @Autowired
    private ManagerIntroService managerIntroService;
    @Autowired
    private IWorkEmployeeService workEmployeeService;
    @Autowired
    private IWorkEmployeeDepartmentService workEmployeeDepartmentService;
    @Autowired
    private IWorkDeptService workDeptService;
    @Autowired
    private RemoteDeptService deptService;
    @Autowired
    private ICorpService corpService;
    @Autowired
    private CpApprovalService cpApprovalService;
    @Autowired
    private Sequence sequence;

    @Override
    public List<ProdGroupVo> getProdGroupTree() {
        Integer corpId = CorpContextHolder.getCorpId();
        List<ProdGroupEntity> prodGroupEntities = prodGroupMapper.selectList(
                Wrappers.<ProdGroupEntity>lambdaQuery().eq(ProdGroupEntity::getCorpId, corpId)
                        // 2-精选活动 6-经理名片 7-今日早报 34-大额存单
                .notIn(ProdGroupEntity::getId, new Integer[] {2, 6, 7, 34})
        );
        List<ProdGroupVo> baseProdGroupVos = prodGroupEntities.stream()
                .map(prodGroupEntity -> {
                    ProdGroupVo prodGroupVo = new ProdGroupVo();
                    prodGroupVo.setId(prodGroupEntity.getId());
                    prodGroupVo.setName(prodGroupEntity.getName());
                    prodGroupVo.setParentId(prodGroupEntity.getParentId());
                    prodGroupVo.setSort(prodGroupEntity.getSort());
                    prodGroupVo.setStatus(prodGroupEntity.getStatus());
                    return prodGroupVo;
                }).collect(Collectors.toList());
        List<ProdGroupVo> prodGroupVos = new ArrayList<>();
        for (ProdGroupVo prodGroupVo : baseProdGroupVos) {
            if (prodGroupVo.getParentId().equals(0)) {
                prodGroupVos.add(prodGroupVo);
            }
            for (ProdGroupVo it : baseProdGroupVos) {
                if (it.getParentId() == prodGroupVo.getId()) {
                    if (prodGroupVo.getChildrens() == null) {
                        prodGroupVo.setChildrens(new ArrayList<>());
                    }
                    prodGroupVo.getChildrens().add(it);
                }
            }
        }
        return prodGroupVos;
    }

    @Override
    public List<ProdDepositEntity> getDeposits(Integer type) {
        Integer corpId = CorpContextHolder.getCorpId();
        return prodDepositMapper.selectList(
                Wrappers.<ProdDepositEntity>lambdaQuery()
                .eq(ProdDepositEntity::getType, type)
                .eq(ProdDepositEntity::getCorpId, corpId)
        );
    }

    @Override
    public List<ProdDepositVo> deposits() {
        List<ProdDepositEntity> entities = prodDepositMapper.selectList(Wrappers.emptyWrapper());
        List<ProdDepositVo> list = new ArrayList<>();

        ProdDepositVo vo36 = new ProdDepositVo();
        Integer type36 = ProductGroupEnum.DEPOSIT_36.getCode();
        List<ProdDepositEntity> entities36 = entities.stream().filter(s -> type36.equals(s.getType())).collect(Collectors.toList());
        ProdDepositEntity maxEntity = entities36.stream().max(Comparator.comparing(ProdDepositEntity::getRate)).get();
        vo36.setType(type36);
        vo36.setName(ProductGroupEnum.DEPOSIT_36.getName());
        vo36.setRateDesc("年利率");
        vo36.setRate(StrUtil.format("{}%", maxEntity.getRate()));
        vo36.setDesc(StrUtil.format("1万起存 5年存期", maxEntity.getDescr()));
        list.add(vo36);

        ProdDepositVo vo31 = new ProdDepositVo();
        Integer type31 = ProductGroupEnum.DEPOSIT_31.getCode();
        List<ProdDepositEntity> entities31 = entities.stream().filter(s -> type31.equals(s.getType())).collect(Collectors.toList());
        ProdDepositEntity minEntity = entities31.stream().min(Comparator.comparing(ProdDepositEntity::getRate)).get();
        maxEntity = entities31.stream().max(Comparator.comparing(ProdDepositEntity::getRate)).get();
        vo31.setType(type31);
        vo31.setName(ProductGroupEnum.DEPOSIT_31.getName());
        vo31.setRateDesc("年利率");
        vo31.setRate(StrUtil.format("{}%-{}%", minEntity.getRate(), maxEntity.getRate()));
        vo31.setDesc("随用随取");
        list.add(vo31);

        ProdDepositVo vo32 = new ProdDepositVo();
        Integer type32 = ProductGroupEnum.DEPOSIT_32.getCode();
        List<ProdDepositEntity> entities32 = entities.stream().filter(s -> type32.equals(s.getType())).collect(Collectors.toList());
        maxEntity = entities32.stream().max(Comparator.comparing(ProdDepositEntity::getRate)).get();
        minEntity = entities32.stream().min(Comparator.comparing(ProdDepositEntity::getRate)).get();
        vo32.setType(type32);
        vo32.setName(ProductGroupEnum.DEPOSIT_32.getName());
        vo32.setRateDesc("年利率");
        vo32.setRate(StrUtil.format("{}%-{}%", minEntity.getRate(), maxEntity.getRate()));
        vo32.setDesc("多种期限可选");
        list.add(vo32);

        ProdDepositVo vo33 = new ProdDepositVo();
        Integer type33 = ProductGroupEnum.DEPOSIT_33.getCode();
        List<ProdDepositEntity> entities33 = entities.stream().filter(s -> type33.equals(s.getType())).collect(Collectors.toList());
        maxEntity = entities33.stream().max(Comparator.comparing(ProdDepositEntity::getRate)).get();
        vo33.setType(type33);
        vo33.setName(ProductGroupEnum.DEPOSIT_33.getName());
        vo33.setRateDesc("年利率");
        vo33.setRate(StrUtil.format("{}%", maxEntity.getRate()));
        vo33.setDesc(maxEntity.getDescr());
        list.add(vo33);

        /*ProdDepositVo vo35 = new ProdDepositVo();
        Integer type35 = ProductGroupEnum.DEPOSIT_35.getCode();
        List<ProdDepositEntity> entities35 = entities.stream().filter(s -> type35.equals(s.getType())).collect(Collectors.toList());
        maxEntity = entities35.stream().max(Comparator.comparing(ProdDepositEntity::getRate)).get();
        vo35.setType(type35);
        vo35.setName(ProductGroupEnum.DEPOSIT_35.getName());
        vo35.setRateDesc("产品年利率");
        vo35.setRate(StrUtil.format("{}%", maxEntity.getRate()));
        vo35.setDesc(maxEntity.getDescr());
        list.add(vo35);*/

        return list;
    }

    @Override
    public R updateDeposit(ProdDepositEntity entity) {
        Integer corpId = CorpContextHolder.getCorpId();
        entity.setType(null);
        entity.setCorpId(corpId);
        return R.ok(prodDepositMapper.updateById(entity));
    }

    @Override
    public List<ProdEntity> getProdList(Integer type) {
        Integer corpId = CorpContextHolder.getCorpId();
        return this.lambdaQuery()
                .eq(ProdEntity::getType, type)
                .eq(ProdEntity::getCorpId, corpId)
                .list();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean saveProd(ProdEntity prodEntity, List<Integer> deptIds) {
        Integer corpId = CorpContextHolder.getCorpId();
        prodEntity.setCorpId(corpId);
        this.baseMapper.insert(prodEntity);
        List<ProdDeptEntity> prodDeptEntities = new ArrayList<>();
        for (Integer deptId : deptIds) {
            ProdDeptEntity prodDeptEntity = new ProdDeptEntity();
            prodDeptEntity.setProductId(prodEntity.getId());
            prodDeptEntity.setDeptId(deptId);
            prodDeptEntities.add(prodDeptEntity);
        }
        return prodDeptService.saveBatch(prodDeptEntities);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateProd(ProdEntity prodEntity, List<Integer> deptIds) {
        this.baseMapper.updateById(prodEntity);
        if (deptIds == null || deptIds.isEmpty())
            return Boolean.TRUE;
        prodDeptService.remove(
                Wrappers.<ProdDeptEntity>lambdaUpdate()
                        .eq(ProdDeptEntity::getProductId, prodEntity.getId())
        );
        List<ProdDeptEntity> prodDeptEntities = new ArrayList<>();
        for (Integer deptId : deptIds) {
            ProdDeptEntity prodDeptEntity = new ProdDeptEntity();
            prodDeptEntity.setProductId(prodEntity.getId());
            prodDeptEntity.setDeptId(deptId);
            prodDeptEntities.add(prodDeptEntity);
        }
        return prodDeptService.saveBatch(prodDeptEntities);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean removeProd(Integer prodId) {
        this.baseMapper.deleteById(prodId);
        return prodDeptService.remove(
                Wrappers.<ProdDeptEntity>lambdaUpdate()
                .eq(ProdDeptEntity::getProductId, prodId)
        );
    }

    @Override
    public ProdDto getProd(Integer prodId) {
        ProdEntity prodEntity = this.baseMapper.selectById(prodId);
        ProdDto prodDto = new ProdDto();
        BeanUtil.copyProperties(prodEntity, prodDto);
        List<Integer> deptIds = prodDeptService.list(
                Wrappers.<ProdDeptEntity>lambdaQuery()
                .eq(ProdDeptEntity::getProductId, prodId)
        ).stream().map(ProdDeptEntity::getDeptId).collect(Collectors.toList());
        prodDto.setDeptIds(deptIds);
        return prodDto;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean syn(Integer synType) {
//        List<Integer> allZhLine = deptService.getAllZhLine();
        List<ProdDeptEntity> saveRelations = new ArrayList<>();
//        Integer corpId = CorpContextHolder.getCorpId();
        CorpEntity corpEntity = corpService.getOne(Wrappers.emptyWrapper(), false);
        if (corpEntity == null) {
            log.error("企业未创建");
            return false;
        }
        Integer corpId = corpEntity.getCorpId();
//
        List<ProdVo> prodVos = synProdInfoMapper.getAllProd(synType);
        List<SyncCycleSetInfoEntity> cycles = syncCycleSetInfoMapper.selectList(
                Wrappers.<SyncCycleSetInfoEntity>lambdaQuery()
                .eq(SyncCycleSetInfoEntity::getDelFlag, 0)
        );
//        List<SyncStdDataInfoEntity> stdDatas = syncStdDataInfoMapper.selectList(Wrappers.emptyWrapper());
        List<SyncAnnualizedRateInfoEntity> annualizedRateInfoEntities = syncAnnualizedRateInfoMapper.selectList(Wrappers.emptyWrapper());
        List<ProdEntity> entityList = new ArrayList<>();
        Integer now = Integer.parseInt(DateUtil.today().replaceAll("-", ""));
        outer:
        for (ProdVo s : prodVos) {
            String prdCode = s.getPrdCode();
            final int[] minAbs = {Integer.MAX_VALUE};
            AtomicReference<SyncCycleSetInfoEntity> entity = new AtomicReference<>();
            cycles.stream().forEach(c -> {
                String nowProduct = c.getPrdCode();
                if (prdCode != null && prdCode.equals(nowProduct)) {
                    int abs = Math.abs(now - c.getCycleUpDate());
                    if (abs < minAbs[0]) {
                        minAbs[0] = abs;
                        entity.set(c);
                    }
                }
            });
            if (entity.get() != null) {
                s.setCycleDate(entity.get().getCycleDate());
                s.setCycleUpDate(entity.get().getCycleUpDate());
                s.setPrevCycleDate(entity.get().getPrevCycleDate());
            }

            if (s == null || (!"0".equals(s.getPrdStatus()) && !"1".equals(s.getPrdStatus()))) {
                continue outer;
            }
            ProdEntity prodEntity = new ProdEntity();
            String showBenchType = s.getShowBenchType();
            prodEntity.setShowBenchType(showBenchType);
            String benchValue = "";
            inner:
            for (SyncAnnualizedRateInfoEntity syncAnnualizedRateInfoEntity : annualizedRateInfoEntities) {
                String code = syncAnnualizedRateInfoEntity.getPrdCode();
                if (prdCode.equals(code)) {
                    if ("0".equals(showBenchType)) {
                        benchValue = syncAnnualizedRateInfoEntity.getMonthClientrate();
                    } else if ("1".equals(showBenchType)) {
                        benchValue = syncAnnualizedRateInfoEntity.getQuarterClientrate();
                    } else if ("3".equals(showBenchType)) {
                        benchValue = syncAnnualizedRateInfoEntity.getHalfyearClientrate();
                    } else if ("4".equals(showBenchType)) {
                        benchValue = syncAnnualizedRateInfoEntity.getYearClientrate();
                    } else if ("5".equals(showBenchType)) {
                        benchValue = syncAnnualizedRateInfoEntity.getHoldClientrate();
                    }
                    break inner;
                }
            }
            if (benchValue != null && !benchValue.isEmpty()) {
                benchValue = String.valueOf(Double.parseDouble(benchValue) * 100);
            }
            prodEntity.setBenchValue(benchValue);
            prodEntity.setRate(parse(s.getYearRate()));
            prodEntity.setCode(s.getPrdCode());
            prodEntity.setOpenCycle(s.getOpenCycle());
            prodEntity.setPrdLable(s.getPrdLable());
            prodEntity.setPrdInfo(s.getPrdInfo());
            prodEntity.setDebtRegistCode(s.getDebtRegistCode());
            prodEntity.setName(s.getPrdName());
            prodEntity.setProductAddress(s.getPrdName2());
            prodEntity.setPrdAttr(s.getPrdAttr());
            prodEntity.setTaName(s.getTaName());
            prodEntity.setPFirstAmt(s.getPFirstAmt());
            prodEntity.setPMaxAmt(s.getPMaxAmt());
            if (s != null && s.getRiskLevel() != null && (s.getRiskLevel() == 0 || s.getRiskLevel() == 1 || s.getRiskLevel() == 2 || s.getRiskLevel() == 3 || s.getRiskLevel() == 4)) {
                prodEntity.setRiskLevel(s.getRiskLevel());
            } else {
                prodEntity.setRiskLevel(5);
            }
            prodEntity.setPrdInvestType(s.getPrdInvestType());
            prodEntity.setOpenTime(s.getOpenTime());
            prodEntity.setCloseTime(s.getCloseTime());
            prodEntity.setStartTime(parseDate(s.getEstabDate()));
            prodEntity.setEndTime(parseDate(s.getEndDate()));
            prodEntity.setIpoStartDate(parseDate(s.getIpoStartDate()));
            prodEntity.setIpoEndDate(parseDate(s.getIpoEndDate()));
            prodEntity.setNavDate(parseDate1(s.getNavDate()));
//            prodEntity.setNav(s.getNav() == null ? s.getNav() : s.getNav().multiply(new BigDecimal(100)));
            prodEntity.setNav(s.getNav());
            String prdType = s.getPrdType();
            prodEntity.setType("0".equals(prdType) ? 12 : ("1".equals(prdType) ? 11 : null));
            if ("0".equals(prdType)) {
                if (s != null && s.getGrade() != null && s.getGrade() == 5) {
                    prodEntity.setStatus(1);
                } else {
                    prodEntity.setStatus(0);
                }
            }
            prodEntity.setState(2);
            prodEntity.setCorpId(corpId);
            prodEntity.setDayRate(parse(s.getDayRate()));
            prodEntity.setYearRate(parse(s.getYearRate()));
            prodEntity.setPrdLable(s.getPrdLable());
            prodEntity.setPAppAmt(s.getPAppAmt());
            prodEntity.setPMaxAmt(s.getPMaxAmt());
            prodEntity.setPrdStatus(s.getPrdStatus());
            prodEntity.setIncomeUnit(s.getIncomeUnit() == null ? s.getIncomeUnit() : s.getIncomeUnit().multiply(new BigDecimal(100)));
            prodEntity.setYield(s.getYield() == null ? s.getYield() : s.getYield().multiply(new BigDecimal(100)));
            prodEntity.setModelComment(s.getModelComment());
            prodEntity.setTransWay(s.getTransWay());
            prodEntity.setInterestDays(s.getInterestDays());
            prodEntity.setTaCode(s.getTaCode());
            prodEntity.setBenchExplainDetail(s.getBenchExplainDetail());
            String orgReserve1 = s.getReserve1();
            if ("D303".equals(orgReserve1)) {
                prodEntity.setReserve1("1303");
            } else if ("D310".equals(orgReserve1)) {
                prodEntity.setReserve1("1309");
            } else if ("D301".equals(orgReserve1)) {
                prodEntity.setReserve1("1301");
            } else {
                prodEntity.setReserve1(orgReserve1);
            }
            prodEntity.setCycleUpDate(s.getCycleUpDate());
            prodEntity.setCycleDate(s.getCycleDate());
            prodEntity.setPrevCycleDate(parseDate(s.getPrevCycleDate()));
            entityList.add(prodEntity);
        }
        // 避免主键值一直递增过大，这里采用增量更新
        Map<String, ProdEntity> entityMap = new HashMap<>();
        entityList.forEach(e -> entityMap.put(e.getCode() + e.getCycleUpDate(), e));

        Integer type = synType == 0 ? 12 : 11;
        List<ProdEntity> oldList = this.list(Wrappers.<ProdEntity>lambdaQuery().eq(ProdEntity::getType, type));
        Map<String, ProdEntity> oldMap = new HashMap<>();
        oldList.forEach(e -> oldMap.put(e.getCode() + e.getCycleUpDate(), e));

        List<ProdEntity> newList = new ArrayList<>();
        List<ProdEntity> updateList = new ArrayList<>();
        List<Integer> delList = new ArrayList<>();

        // 过滤新增
        oldList.forEach(e -> entityMap.remove(e.getCode() + e.getCycleUpDate()));
        newList.addAll(entityMap.values());

        // 过滤删除和更新
        entityList.forEach(e -> {
            ProdEntity oldEntity = oldMap.remove(e.getCode() + e.getCycleUpDate());
            if (oldEntity != null) {
                e.setId(oldEntity.getId());
                updateList.add(e);
            }
        });
        oldMap.forEach((k, e) -> delList.add(e.getId()));

        // 新增
        if (!newList.isEmpty()) {
            this.saveBatch(newList);
            /*if (allZhLine != null) {
                newList.forEach(s -> {
                    Integer prodId = s.getId();
                    allZhLine.forEach(l -> {
                        ProdDeptEntity prodDeptEntity = new ProdDeptEntity();
                        prodDeptEntity.setProductId(prodId);
                        prodDeptEntity.setDeptId(l);
                        saveRelations.add(prodDeptEntity);
                    });
                });
            }
            if (!saveRelations.isEmpty()) {
                prodDeptService.saveBatch(saveRelations);
            }*/
        }
        // 更新
        if (!updateList.isEmpty()) {
            this.updateBatchById(updateList);
        }
        // 删除原有产品数据
        if (!delList.isEmpty()) {
            this.removeByIds(delList);
            /*if (delList != null && delList.size() > 0) {
                prodDeptService.remove(
                        Wrappers.<ProdDeptEntity>lambdaUpdate()
                        .in(ProdDeptEntity::getDeptId, delList)
                );
            }*/
        }

        return Boolean.TRUE;
    }

    public IPage<ProdEntity> product(Integer status, List<Integer> deptIds, Page page) {
        Integer corpId = CorpContextHolder.getCorpId();
        IPage<ProdEntity> prodEntities = this.baseMapper.product(page, status, corpId, deptIds);
        return prodEntities;
    }

    public IPage<ProdEntity> other(Integer status, Integer type, List<Integer> deptIds, Page page) {
        Integer corpId = CorpContextHolder.getCorpId();
        DateTime now = new DateTime();
        IPage<ProdEntity> prodEntities;
        prodEntities = this.baseMapper.other(page, status, type, corpId, deptIds, now);
        return prodEntities;
    }

    public IPage<ProdEntity> other1(String searchStr, Integer riskLevel, String prdAttr, Integer status, Integer type, Page page) {
        Integer corpId = CorpContextHolder.getCorpId();
        IPage<ProdEntity> prodEntities;
        prodEntities = this.baseMapper.other1(page, status, type, corpId, riskLevel, prdAttr, searchStr);
        return prodEntities;
    }

    public List<ProdEntity> otherFinance(Integer status) {
        Integer corpId = CorpContextHolder.getCorpId();
        DateTime now = new DateTime();
        List<ProdEntity> prodEntities;
        prodEntities = this.baseMapper.otherFinance(status, corpId, now);
        return prodEntities;
    }

    @Override
    public BusinessCardVO getCustomerManagerDetails(String wxUserId) {
        String intro = ProductConstant.INTRO;
        BusinessCardVO vo = new BusinessCardVO();
        WorkEmployeeEntity employeeEntity = workEmployeeService.getOne(new LambdaQueryWrapper<WorkEmployeeEntity>()
                .eq(WorkEmployeeEntity::getCorpId, CorpContextHolder.getCorpId())
                .eq(WorkEmployeeEntity::getWxUserId, wxUserId));
        if (employeeEntity != null) {
            WorkEmployeeDepartmentEntity employeeDepartmentEntity = workEmployeeDepartmentService.getOne(new LambdaQueryWrapper<WorkEmployeeDepartmentEntity>()
                    .eq(WorkEmployeeDepartmentEntity::getEmployeeId, employeeEntity.getId()));
            WorkDeptEntity deptEntity = workDeptService.getById(employeeDepartmentEntity.getDepartmentId());
            vo.setJobNo(employeeEntity.getWxUserId());
            vo.setUserName(employeeEntity.getName());
            vo.setPostName(employeeEntity.getPosition());
            vo.setMobile(employeeEntity.getMobile());
            vo.setOrgName(deptEntity.getName());
            vo.setOrgAddr(deptEntity.getAddress());
            JSONObject jsonObject = JSONObject.parseObject(employeeEntity.getExtattr());
            if (jsonObject == null || jsonObject.isEmpty() || jsonObject.get("qualification") == null) {
                vo.setQualifications(new ArrayList<String>());
            } else {
                ArrayList<String> qualifications = new ArrayList<>();
                JSONArray jsonArray = JSONArray.parseArray(jsonObject.get("qualification").toString());
                jsonArray.forEach(j->{
                    if (j instanceof JSONObject) {
                        JSONObject qualificationObject = JSONObject.parseObject(j.toString());
                        if (qualificationObject == null || qualificationObject.isEmpty()) {
                            return;
                        }
                        String textStr = qualificationObject.get("text").toString();
                        qualifications.add(JSONObject.parseObject(textStr).get("value").toString());
                    } else {
                        return;
                    }
                });
                vo.setQualifications(qualifications);
            }
        }

        ManagerIntroEntity introEntity = managerIntroService.getOne(new LambdaQueryWrapper<ManagerIntroEntity>()
                .eq(ManagerIntroEntity::getWxUserId, wxUserId)
                .eq(ManagerIntroEntity::getCorpId, CorpContextHolder.getCorpId()));
        if (introEntity != null && !StrUtil.isBlank(introEntity.getIntro())) {
            vo.setIntro(introEntity.getIntro());
        } else {
            vo.setIntro(intro);
        }
        vo.setMgrAvatar(introEntity == null ? "" : introEntity.getMgrAvatar());
        String respJson = WxApiUtils.getUser(wxUserId, CorpContextHolder.getCorpId());
        JSONObject jsonObject = JSON.parseObject(respJson);
        vo.setQrcode(jsonObject.getString("qr_code"));
        return vo;
    }

    @Override
    public Boolean editIntroduction(UpdateIntroDTO dto) {
        ManagerIntroEntity introEntity = new ManagerIntroEntity();
        introEntity.setCorpId(CorpContextHolder.getCorpId());
        introEntity.setIntro(dto.getIntroText());
        introEntity.setWxUserId(dto.getWxUserId());
        ManagerIntroEntity result = managerIntroService.getOne(new LambdaQueryWrapper<ManagerIntroEntity>()
                .eq(ManagerIntroEntity::getCorpId, CorpContextHolder.getCorpId())
                .eq(ManagerIntroEntity::getWxUserId, dto.getWxUserId()));
        if (result == null) {
            return managerIntroService.save(introEntity);
        } else {
            return managerIntroService.update(introEntity,new LambdaQueryWrapper<ManagerIntroEntity>()
                    .eq(ManagerIntroEntity::getCorpId,CorpContextHolder.getCorpId())
                    .eq(ManagerIntroEntity::getWxUserId,dto.getWxUserId()));
        }
    }

    @Override
    public R<SysFileVo> managerAvatarUpload(String wxUserId, String mediaId) {
        WorkEmployeeEntity employeeEntity = workEmployeeService.getOne(new LambdaQueryWrapper<WorkEmployeeEntity>()
                .eq(WorkEmployeeEntity::getCorpId, CorpContextHolder.getCorpId())
                .eq(WorkEmployeeEntity::getWxUserId, wxUserId));
        if (employeeEntity == null) {
            throw new IllegalArgumentException("未找到wxUserId:"+wxUserId);
        }
//        String respJson = WxApiUtils.getFromTemp(CorpContextHolder.getCorpId(), mediaId);
//        if (respJson == null) {
//            throw new IllegalArgumentException("无效的mediaId");
//        }
        String avatarKey = FileUtils.getFileNameOfManagerAvatar();
        String url = API_GET_FILE_TO_TEMP + "?access_token=" + getAccessTokenEmployee(CorpContextHolder.getCorpId()) + "&media_id=" + mediaId;
        //上传头像至本地
        SysFileVo sysFileVo = FilesUtil.uploadFileByURL(url, avatarKey);
        sysFileVo.setUrl(FilesUtil.getFileURI(avatarKey));
        ManagerIntroEntity managerIntroEntity = new ManagerIntroEntity();
        managerIntroEntity.setCorpId(CorpContextHolder.getCorpId());
        managerIntroEntity.setWxUserId(wxUserId);
        managerIntroEntity.setMgrAvatar(FilesUtil.getFileURI(avatarKey));
        ManagerIntroEntity result = managerIntroService.getOne(new LambdaQueryWrapper<ManagerIntroEntity>()
                .eq(ManagerIntroEntity::getCorpId, CorpContextHolder.getCorpId())
                .eq(ManagerIntroEntity::getWxUserId, wxUserId));
        if (result == null) {
            managerIntroService.save(managerIntroEntity);
        } else {
            managerIntroService.update(managerIntroEntity,new LambdaQueryWrapper<ManagerIntroEntity>()
                    .eq(ManagerIntroEntity::getCorpId,CorpContextHolder.getCorpId())
                    .eq(ManagerIntroEntity::getWxUserId,wxUserId));
        }
        return R.ok(sysFileVo);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean approval(ProdEntity entity, Integer id, String opinion, Integer state) {
        LocalDateTime onTime = state == 2 ? LocalDateTime.now() : null;
        Integer updateState = 2;
        if (state != null && state == 1) {
            updateState = 4;
        }
        Boolean flag = this.update(
                Wrappers.<ProdEntity>lambdaUpdate()
                        .set(ProdEntity::getState, updateState)
                        .set(ProdEntity::getOpinion, opinion)
                        .set(ProdEntity::getOnTime, onTime)
                        .eq(ProdEntity::getId, id)
        );
        if (flag) {
            Integer createUserId = SecurityUtils.getUser().getId();
            String createUserName = SecurityUtils.getUser().getUsername();
            Long approvalId = sequence.nextValue();
            CpApprovalEntity approvalEntity = new CpApprovalEntity();
            approvalEntity.setId(approvalId);
            approvalEntity.setItemId(String.valueOf(entity.getId()));
            approvalEntity.setItemType(entity.getType());
            approvalEntity.setApprovalPreState(entity.getState());
            approvalEntity.setApprovalPostState(updateState);
            approvalEntity.setApprovalType(state);
            approvalEntity.setApprovalUserId(createUserId);
            approvalEntity.setApprovalUserName(createUserName);
            cpApprovalService.save(approvalEntity);
        }
        return Boolean.TRUE;
    }

    private LocalDateTime parseDate1(Integer date) {
        if (date == 0) return LocalDateTime.parse("0000-00-00 00:00:00");
        try {
            Integer year = date / 10000;
            Integer month = date % 10000 / 100;
            Integer day = date % 10000 % 100;
            return LocalDateTime.of(year, month, day, 0, 0, 0);
        } catch (Exception e) {
            return null;
        }
    }

    private String parseDate(Integer date) {
        if (date == null || date == 0) return null;
        try {
            Integer year = date / 10000;
            Integer month = date % 10000 / 100;
            Integer day = date % 10000 % 100;
            String result = String.format("%04d", Integer.valueOf(year)) + "-"
                    + String.format("%02d", Integer.valueOf(month)) + "-"
                    + String.format("%02d", Integer.valueOf(day)) + " 00:00:00";
            return result;
        } catch (Exception e) {
            return null;
        }
    }

    private void handlerEntity(String reserve1, ProdEntity prodEntity) {
        Integer type = prodEntity.getType();
        if(type.equals(11)) {
            // 后续须根据产品模板信息具体处理
            if ("D303".equals(reserve1)) {
                prodEntity.setDesc1("业绩比较基准");
            } else {
                prodEntity.setDesc1("七日年化收益率");
            }
            prodEntity.setDesc2("中低风险|1万元起购");
            prodEntity.setTermDesc("灵活申赎");
        }
        if(type.equals(12)) {
            prodEntity.setDesc1("近一年涨跌幅");
            prodEntity.setDesc2("中低风险|债券型|100元起购");
        }
    }

    private Float parse(String rate) {
        try {
            return Float.parseFloat(rate);
        } catch (Exception e) {
            return 0f;
        }
    }

}
